/*
* 用户注册页面
* */
import React, {Component, Fragment} from 'react'
import {Form, Input, AutoComplete, Button, Icon} from 'antd'
import {debounce, post} from '../../common/js/utils'
import {Link} from 'react-router-dom'
import {Header} from '../../layout/header'
import './index.scss'

const usernameValidate = debounce(function (rule, value, callback) {
  if (!value) return callback()
  if (/^[a-zA-Z][a-zA-Z\d_]{5,15}$/.test(value)) {
    post('/api/users/exist', {
      username: value
    }).then(res => {
      if (res.data.exist === 1) {
        callback(new Error('用户名已存在'))
      } else {
        callback()
      }
    }).catch(err => {
      callback(err)
    })
  } else {
    callback(new Error('用户名格式不正确'))
  }
}, 800)

const FormItem = Form.Item
const AutoCompleteOption = AutoComplete.Option

class Register extends Component {
  state = {
    success: false
  }

  componentWillMount() {}

  handleSubmit = e => {
    e.preventDefault()
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        post('/api/users/register', values).then(res => {
          if (res.result === 1) {
            this.setState({
              success: true
            })
          }
        })
      }
    })
  }

  render() {
    const {getFieldDecorator} = this.props.form
    const {success} = this.state
    return (
      <Fragment>
        <Header
          onRef={e => this.layout = e}
        />
        <div className="register-bg" />
        <h1 className="register-title">用户注册</h1>
        {
          success
            ? <div
              style={{
                margin: 50,
                textAlign: 'center'
              }}
            >
              <Icon type="check-circle" theme="twoTone" twoToneColor="#52c41a" style={{
                fontSize: 30,
                verticalAlign: 'middle'
              }} />&nbsp;
              <span style={{
                fontSize: 26,
                verticalAlign: 'middle',
                display: 'inline-block'
              }} >恭喜您，注册成功！</span>
              <span onClick={e => this.layout.loginModal.show('/')} style={{
                cursor: 'pointer',
                color: '#1890ff',
                verticalAlign: 'middle',
                display: 'inline-block'
              }} >立即登录</span>
            </div>
            : <Form
              onSubmit={this.handleSubmit}
              style={{
                width: '500px',
                margin: '0 auto'
              }}
            >
              <FormItem
                {...formLayout}
                label="用户名"
              >
                {
                  getFieldDecorator('username', {
                    rules: [{
                      required: true,
                      message: '请输入用户名'
                    }, {
                      validator: usernameValidate
                    }]
                  })(<Input placeholder="请输入用户名（登录账号）"/>)
                }
              </FormItem>
              <FormItem
                {...formLayout}
                label="昵称"
              >
                {
                  getFieldDecorator('nickname', {
                    rules: [{
                      required: true,
                      message: '请输入昵称'
                    }, {
                      max: 12,
                      message: '昵称最多12个字符'
                    }]
                  })(<Input placeholder="请输入昵称"/>)
                }
              </FormItem>
              <FormItem
                {...formLayout}
                label="E-mail"
              >
                {
                  getFieldDecorator('email', {
                    rules: [{
                      required: true,
                      message: '请输入邮箱'
                    }, {
                      type: 'email',
                      message: '请输入正确的邮箱'
                    }]
                  })(<AutoEmail/>)
                }
              </FormItem>
              <FormItem
                {...formLayout}
                label="密码"
              >
                {
                  getFieldDecorator('password', {
                    rules: [{
                      required: true,
                      message: '请输入密码'
                    }, {
                      validator(rule, value, callback) {
                        if (!value) return callback()
                        if (passwordValid(value)) {
                          callback()
                        } else {
                          callback(new Error('密码格式不正确'))
                        }
                      }
                    }]
                  })(<Input type="password" placeholder="请输入密码"/>)
                }
              </FormItem>
              <FormItem
                {...formLayout}
                label="确认密码"
              >
                {
                  getFieldDecorator('password2', {
                    rules: [{
                      required: true,
                      message: '请再次输入密码'
                    }, {
                      validator: (rule, value, callback) => {
                        if (value && value !== this.props.form.getFieldValue('password')) {
                          callback(new Error('两次密码不一致'))
                        } else {
                          callback()
                        }
                      }
                    }]
                  })(<Input type="password" placeholder="请再次输入密码"/>)
                }
              </FormItem>
              <FormItem
                {...formControlLayout}
              >
                <Button type="primary" htmlType="submit">注册</Button>
                &nbsp;&nbsp;&nbsp;
                <span>已有账号，</span>
                <span onClick={e => this.layout.loginModal.show('/')} style={{
                  cursor: 'pointer',
                  color: '#1890ff'
                }} >登录</span>
                &nbsp;&nbsp;&nbsp;or&nbsp;&nbsp;&nbsp;
                <Link to="/">回到首页</Link>
              </FormItem>
            </Form>
        }
      </Fragment>
    )
  }
}

export default Form.create()(Register)

export const passwordValid = str => /^[a-zA-Z\d_]{6,16}$/.test(str)

export const formLayout = {
  labelCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 8
    }
  },
  wrapperCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 16
    }
  }
}

export const formControlLayout = {
  wrapperCol: {
    xs: {
      span: 20,
      offset: 4
    },
    sm: {
      span: 16,
      offset: 8
    }
  }
}

export class AutoEmail extends Component {

  state = {
    autoComplete: []
  }

  handleChange = value => {
    this.props.onChange && this.props.onChange(value)
    const domains = ['@qq.com', '@163.com', '@126.com']
    let hasCom = value.indexOf('@') !== -1

    if (value && !hasCom) {
      this.setState({
        autoComplete: domains.map(item => `${value}${item}`)
      })
    } else {
      this.setState({
        autoComplete: []
      })
    }
  }

  render() {
    const {autoComplete} = this.state
    const options = autoComplete.map(item => (
      <AutoCompleteOption key={item}>{item}</AutoCompleteOption>
    ))

    return (
      <AutoComplete
        {...this.props}
        dataSource={options}
        onChange={this.handleChange}
        placeholder="请输入邮箱"
      >
        <Input />
      </AutoComplete>
    )
  }
}
